<template>
  <view class="coupon-detail">
    <uni-nav-bar 
      :title="isEdit ? '编辑优惠券' : '新增优惠券'" 
      left-icon="back" 
      @clickLeft="goBack"
      background-color="#1890ff"
      color="#fff"
    />
    
    <view class="form-container">
      <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <uni-forms-item label="名称" name="name" required>
          <uni-easyinput v-model="formData.name" placeholder="请输入优惠券名称" />
        </uni-forms-item>
        
        <uni-forms-item label="类型" name="type" required>
          <uni-data-select v-model="formData.type" :localdata="couponTypeOptions" @change="onTypeChange"></uni-data-select>
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.type === CouponType.Discount" label="折扣(折)" name="value" required>
          <uni-easyinput v-model="formData.value" type="digit" placeholder="请输入折扣，如8.5表示8.5折" />
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.type === CouponType.Cash" label="面额(元)" name="value" required>
          <uni-easyinput v-model="formData.value" type="digit" placeholder="请输入现金券面额" />
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.type === CouponType.Reduction" label="满减金额(元)" name="value" required>
          <uni-easyinput v-model="formData.value" type="digit" placeholder="请输入减免金额" />
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.type === CouponType.Reduction" label="最低消费(元)" name="min_consume" required>
          <uni-easyinput v-model="formData.min_consume" type="digit" placeholder="请输入最低消费金额" />
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.type === CouponType.Duration" label="时长(分钟)" name="duration" required>
          <uni-easyinput v-model="formData.duration" type="number" placeholder="请输入赠送时长" />
        </uni-forms-item>
        
        <uni-forms-item label="库存" name="total_count" required>
          <uni-easyinput v-model="formData.total_count" type="number" placeholder="请输入库存数量" />
        </uni-forms-item>
        
        <uni-forms-item label="状态" name="status" required>
          <uni-data-select v-model="formData.status" :localdata="statusOptions"></uni-data-select>
        </uni-forms-item>
        
        <uni-forms-item label="有效期" name="valid_range" required>
          <uni-datetime-picker 
            v-model="formData.valid_range" 
            type="daterange" 
            rangeSeparator="至"
            placeholder="请选择有效期"
          />
        </uni-forms-item>
        
        <uni-forms-item label="可用时间" name="time_range">
          <uni-datetime-picker 
            v-model="formData.time_range" 
            type="timerange" 
            rangeSeparator="至"
            placeholder="请选择可用时间段"
          />
        </uni-forms-item>
        
        <uni-forms-item label="可用星期" name="available_weekdays">
          <uni-data-checkbox multiple v-model="formData.available_weekdays" :localdata="weekOptions"></uni-data-checkbox>
        </uni-forms-item>
        
        <uni-forms-item label="适用范围" name="applicable_type" required>
          <uni-data-select v-model="formData.applicable_type" :localdata="scopeOptions"></uni-data-select>
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.applicable_type === ApplicableType.Store" label="适用门店" name="applicable_ids">
          <uni-data-checkbox multiple v-model="formData.applicable_ids" :localdata="storeOptions"></uni-data-checkbox>
        </uni-forms-item>
        
        <uni-forms-item v-if="formData.applicable_type === ApplicableType.Venue" label="适用场地" name="applicable_ids">
          <uni-data-checkbox multiple v-model="formData.applicable_ids" :localdata="venueOptions"></uni-data-checkbox>
        </uni-forms-item>
        
        <uni-forms-item label="描述" name="description">
          <uni-easyinput v-model="formData.description" type="textarea" placeholder="请输入优惠券描述" />
        </uni-forms-item>
      </uni-forms>
      
      <view class="form-actions">
        <button class="submit-btn" @click="handleSubmit">{{ isEdit ? '更新' : '创建' }}</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import type { Coupon } from '@/types/coupon';
import { CouponType, ApplicableType } from '@/types/coupon';
import { fetchCouponDetail, createCoupon, updateCoupon } from '@/api/coupon';

// 页面参数
const isEdit = ref(false);
const couponId = ref<number | null>(null);

// 表单引用
const formRef = ref<any>(null);

// 表单数据
const formData = reactive<any>({
  name: '',
  type: CouponType.Cash,
  status: 1,
  total_count: 100,
  value: null,
  min_consume: null,
  duration: null,
  valid_range: [],
  time_range: [],
  available_weekdays: [],
  applicable_type: ApplicableType.All,
  applicable_ids: [],
  description: '',
});

// 表单验证规则
const rules = {
  name: { rules: [{ required: true, errorMessage: '请输入名称' }] },
  type: { rules: [{ required: true, errorMessage: '请选择类型' }] },
  total_count: { rules: [{ required: true, errorMessage: '请输入库存' }] },
  value: { rules: [{ required: true, errorMessage: '请输入值' }] },
  min_consume: { rules: [{ required: true, errorMessage: '请输入最低消费' }] },
  valid_range: { rules: [{ required: true, errorMessage: '请选择有效期' }] },
  applicable_type: { rules: [{ required: true, errorMessage: '请选择适用范围' }] },
};

// 选项数据
const couponTypeOptions = [
  { value: CouponType.Discount, text: '折扣券' },
  { value: CouponType.Cash, text: '现金券' },
  { value: CouponType.Reduction, text: '满减券' },
  { value: CouponType.Duration, text: '时长券' },
];

const statusOptions = [
  { value: 1, text: '启用' },
  { value: 0, text: '禁用' },
];

const scopeOptions = [
  { value: ApplicableType.All, text: '全场通用' },
  { value: ApplicableType.Store, text: '指定门店' },
  { value: ApplicableType.Venue, text: '指定场地' },
];

const weekOptions = [
  { value: 1, text: '周一' },
  { value: 2, text: '周二' },
  { value: 3, text: '周三' },
  { value: 4, text: '周四' },
  { value: 5, text: '周五' },
  { value: 6, text: '周六' },
  { value: 0, text: '周日' },
];

const storeOptions = ref([
  { value: 1, text: '总店' },
  { value: 2, text: '分店A' },
  { value: 3, text: '分店B' },
]);

const venueOptions = ref([
  { value: 1, text: '场地A' },
  { value: 2, text: '场地B' },
  { value: 3, text: '场地C' },
]);

// 页面加载
onLoad((options: any) => {
  if (options.id) {
    isEdit.value = true;
    couponId.value = parseInt(options.id);
    getCouponInfo();
  }
});

// 类型变化处理
const onTypeChange = () => {
  formData.value = null;
  formData.min_consume = null;
  formData.duration = null;
};

// 获取优惠券详情
const getCouponInfo = async () => {
  if (!couponId.value) return;
  
  try {
    const res = await fetchCouponDetail(couponId.value);
    
    // 基本信息
    formData.name = res.name;
    formData.type = res.type;
    formData.status = res.status;
    formData.total_count = res.total_count;
    formData.description = res.description || '';
    formData.applicable_type = res.applicable_type;
    formData.applicable_ids = res.applicable_ids || [];
    formData.available_weekdays = res.available_weekdays || [];
    
    // 时间范围
    if (res.valid_start_time && res.valid_end_time) {
      formData.valid_range = [res.valid_start_time, res.valid_end_time];
    }
    if (res.available_start_time && res.available_end_time) {
      formData.time_range = [res.available_start_time, res.available_end_time];
    }
    
    // 根据类型设置值
    if (res.type === CouponType.Cash || res.type === CouponType.Reduction) {
      formData.value = res.value ? res.value / 100 : 0;
    }
    if (res.type === CouponType.Reduction) {
      formData.min_consume = res.min_consume ? res.min_consume / 100 : 0;
    }
    if (res.type === CouponType.Discount) {
      formData.value = res.discount ? res.discount / 10 : 0;
    }
    if (res.type === CouponType.Duration) {
      formData.duration = res.duration || 0;
    }
  } catch (error) {
    console.error('获取优惠券详情失败:', error);
    uni.showToast({
      title: '获取详情失败',
      icon: 'none'
    });
  }
};

// 提交处理
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate();
    if (!valid) return;
    
    const dataToSubmit: any = { ...formData };
    
    // 处理金额字段（转换为分）
    if (dataToSubmit.type === CouponType.Cash || dataToSubmit.type === CouponType.Reduction) {
      dataToSubmit.value = Number(formData.value) * 100;
    }
    if (dataToSubmit.type === CouponType.Reduction) {
      dataToSubmit.min_consume = Number(formData.min_consume) * 100;
    }
    if (dataToSubmit.type === CouponType.Discount) {
      dataToSubmit.discount = Number(formData.value) * 10;
      delete dataToSubmit.value;
    }
    if (dataToSubmit.type === CouponType.Duration) {
      dataToSubmit.duration = Number(formData.duration);
      delete dataToSubmit.value;
    }
    
    // 处理数量
    dataToSubmit.total_count = Number(formData.total_count);
    
    // 处理时间范围
    if (formData.valid_range && formData.valid_range.length === 2) {
      dataToSubmit.valid_start_time = formData.valid_range[0];
      dataToSubmit.valid_end_time = formData.valid_range[1];
    }
    if (formData.time_range && formData.time_range.length === 2) {
      dataToSubmit.available_start_time = formData.time_range[0];
      dataToSubmit.available_end_time = formData.time_range[1];
    }
    
    // 删除不需要的字段
    delete dataToSubmit.valid_range;
    delete dataToSubmit.time_range;
    
    if (isEdit.value && couponId.value) {
      await updateCoupon(couponId.value, dataToSubmit);
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      });
    } else {
      await createCoupon(dataToSubmit);
      uni.showToast({
        title: '创建成功',
        icon: 'success'
      });
    }
    
    setTimeout(() => {
      goBack();
    }, 1500);
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 返回
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.coupon-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.form-container {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
  padding: 0 20px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
}

.submit-btn:active {
  background-color: #096dd9;
}
</style>